import datetime
import os
from update import update

PATH = os.path.dirname(__file__)
PATH = os.path.join(PATH, "statics")

del_list = [
    ".Identifier",
    ":SmartScreen",
]
ignore_list = [
    ".git",
    "cache",
]


def clean(path):
    "清理垃圾"
    files = []
    print(f"开始遍历【{path}】查找要清理的文件...\n找到以下待删除文件：")
    for filepath, dirnames, filenames in os.walk(path):
        for filename in filenames:
            path = os.path.join(filepath, filename)
            flag = 1
            for i in ignore_list:
                if i in path:
                    flag = 0
            if flag:
                # print(path)
                if path.endswith(".cpp"):
                    if os.path.isfile(path[:-4]):
                        path = path[:-4]
                        files.append(path)
                        print(f"  {path}")
                    elif os.path.isfile(path[:-4] + ".exe"):
                        path = path[:-4] + ".exe"
                        files.append(path)
                        print(f"  {path}")
                elif path.endswith(".c"):
                    if os.path.isfile(path[:-2]):
                        path = path[:-2]
                        files.append(path)
                        print(f"  {path}")
                    elif os.path.isfile(path[:-2] + ".exe"):
                        path = path[:-2] + ".exe"
                        files.append(path)
                        print(f"  {path}")
                else:
                    flag = 0
                    for x in del_list:
                        if filename.endswith(x):
                            flag = 1
                            break
                    if flag:
                        files.append(path)
                        print(f"  {path}")
    print("\n删除队列创建成功，开始删除...")
    for path in files:
        try:
            os.remove(path)
            print(f"删除【{path}】文件成功！")
        except:
            print(f"删除【{path}】文件失败！")


def sync(path):
    "同步"
    from teachzero.settings import SYNC_FOLDERS
    folders = []
    for fold in SYNC_FOLDERS:
        if os.path.isdir(os.path.join(path, fold)):
            folders.append(os.path.join(path, fold))
    for i in os.listdir(os.path.join(path, "lesson")):
        if not i.startswith("."):
            p = os.path.join(path, "lesson", i)
            if os.path.isdir(p):
                folders.append(p)
    folders.sort()
    for folder in folders:
        if os.path.isdir(folder):
            sync_folder(folder)
        else:
            print(f"\n【{folder}】不存在，暂不同步。\n")


def sync_folder(folder):
    s = f"开始拉取并同步【{folder}】文件夹的远程分支..."
    print(f"#" * 100)
    print(s)
    print("-" * 100)
    os.chdir(folder)
    if datetime.datetime.now().weekday() == 0 and datetime.datetime.now().hour == 2:
        os.system(f'git gc --prune=now')  # 每周一晚上2点执行gc
    os.system(f"git fetch")
    os.system(f"git merge")
    os.system(f"git add .")
    os.system(f'git commit -am "{datetime.date.today()}日更新"')
    os.system("git push")
    s = f"【{folder}】文件夹同步完成\n"
    print(f"{s:<100}")


def sync_blog(path):
    """同步"""
    print("开始同步工程目录...")
    os.chdir(path)
    if datetime.datetime.now().weekday() == 0 and datetime.datetime.now().hour == 2:
        os.system(f'git gc --prune=now')  # 每周一晚上2点执行gc
    os.system("git fetch")
    os.system("git merge")
    os.system("git add .")
    os.system(f'git commit -am "{datetime.date.today()}更新"')
    os.system("git push")
    path = os.path.dirname(path)
    path = os.path.join(path, "statics")
    print(path)
    print("工程目录同步完毕，开始开始清理文件...")
    clean(path)
    print("清理完毕，开始同步...")
    sync(path)
    print("所有文件同步完成，谢谢使用！\n")
    path = os.path.dirname(path)
    path = os.path.join(path, "blog")
    os.chdir(path)
    print("#" * 50 + "\n工程目录同步完成，开始解析数据并更新数据库...")
    update()
    print("#" * 50 + "\n数据库更新完成，谢谢使用。")


if __name__ == "__main__":
    sync_blog(os.path.dirname(__file__))  # 同步
